package com.example.frn.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.frn.dao.UserMapper;
import com.example.frn.dto.UserModifyPasswdDto;
import com.example.frn.entity.User;
import com.example.frn.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String username, String passwd) {
        User user = userMapper.selectUserByUsername(username);
        if(user !=null){// 用户名错误或账号已删除
            String secretPasswd = SecureUtil.md5(passwd);
            if(secretPasswd.equals(user.getPasswd())){
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean save(User user) {
        String passwd=user.getPasswd();
        String secretPasswd = SecureUtil.md5(passwd);
        user.setPasswd(secretPasswd);
        return userMapper.insert(user)>0;
    }

    @Override
    public boolean updateById(User user) {
        return userMapper.updateById(user)>0;
    }

    @Override
    public boolean removeById(Integer id) {
        return userMapper.deleteById(id)>0;
    }

    @Override
    public boolean modifyPasswd(UserModifyPasswdDto dto) {
        //1.先判断旧密码对不对
        //从数据库中查出加密后的旧密码
        String secretPasswd=userMapper.selectById(dto.getId()).getPasswd();
        String oldPasswd = dto.getOldPasswd();
        if(!SecureUtil.md5(oldPasswd).equals(secretPasswd))
            return false;//旧密码不正确
        //2 对密码进行加密
        User user = new User();
        user.setId(dto.getId());
        user.setPasswd(SecureUtil.md5(dto.getNewPasswd()));
        return userMapper.updatePasswd(user)>0;
    }

    @Override
    public boolean modifyNoSpeak(User user) {
        return userMapper.updateNoSpeakStatus(user)>0;
    }

    @Override
    public User getById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public PageInfo<User> page(Integer pageNum, Integer pageSize, String username, String nickName) {
        PageHelper.startPage(pageNum,pageSize);
        if(username!=null) username=username.trim();
        if(nickName!=null) nickName=nickName.trim();
        List<User> list =userMapper.List(username,nickName);
        return new PageInfo<>(list);
    }




}
